package com.zbo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录拦截器 - 保护需要登录才能访问的资源
 */
@WebFilter(filterName = "LoginFilter",
        urlPatterns = {
                "/homeServlet",           // 课表页面
                "/api/timetable/*",     // 课表 API
                "/api/course/*",        // 课程 API
                "/api/sc/*"             // 学生课程 API
        })
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        // 1. 检查用户是否已登录（Session 中是否有 studentId）
        Integer studentId = (Integer) session.getAttribute("studentId");

        if (studentId != null) {
            // 已登录，放行请求
            chain.doFilter(request, response);
        } else {
            // 未登录，重定向到登录页
            String contextPath = req.getContextPath();
            resp.sendRedirect(contextPath + "/login.html");
        }
    }

    @Override
    public void destroy() {

    }
}